package org.cos.verification.sample;

import java.io.*;

import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.TextBox;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;

import org.kxml2.io.KXmlParser;
import org.xmlpull.v1.XmlPullParser;

public class SampleKXml extends MIDlet {
	private TextBox tbox = null;
	
	public SampleKXml() {
		tbox = new TextBox("", "Hello", 4000, 0);
	}
	
	protected void destroyApp(boolean arg0) throws MIDletStateChangeException {		
		;
	}

	protected void pauseApp() {
		;
	}

	protected void startApp() throws MIDletStateChangeException {
		String str = 
			"<!-- 大写字母表示替换为真实值 --> "
		+ "<file>  <!-- 每个model文件可能包含若干类 -->"
		+ " <class>"
		+ "   <state>  <!-- 每个类多个状态 -->"
		+ "     <trans>  <!-- 每个状态多个转移 -->"
		+ "       <method>METHOD_INDEX</method>"
		+ "       <tail>TAIL_STATE_INDEX</tail>"
		+ "       <con type='INT/STR/VAR'>  <!-- 每个转移多个条件 -->"
		+ "         <rel>0/1/2</rel>  <!-- 相对于比较值的关系 -->"
		+ "         <val>VALUE</val>  <!-- 比较值 -->"
		+ "       </con>"
		+ "       <act type='STACK/VAR'>  <!-- 每个状态多个动作 -->"
		+ "         <type>0/1</type>  <!-- 表示动作PUSH/POP -->"
		+ "         <val>VALUE</val>  <!-- 栈顶值 -->"
		+ "       </act>"
		+ "     </trans>"
		+ "   </state>"
		+ " </class>"
		+ "</file>";

		
		tbox.setString(testParse(str));
		Display.getDisplay(this).setCurrent(tbox);
	}

	/**
	 */
	public String testParse(String xmlStr) {
		String outstr = null;
		try {
			byte[] ss = xmlStr.getBytes();

			KXmlParser parser = new KXmlParser();

			parser.setInput(new InputStreamReader(
							new ByteArrayInputStream(ss)));
			int eventType = parser.getEventType();
			while (eventType != XmlPullParser.END_DOCUMENT) {
				if (eventType == XmlPullParser.START_DOCUMENT) {
					outstr += "\nThe NAME of This Tag：" + parser.getName();
					outstr += "\nThe Attr of this Tag：";

					int attrCount = parser.getAttributeCount();
					for (int i = 0; i < attrCount; i++) {
						outstr += parser.getAttributeName(i);
					}
				} else if (eventType == XmlPullParser.START_TAG) {
					outstr += "\n[Enter Tag `" + parser.getName() + "']";
					int attrCount = parser.getAttributeCount();
					if (attrCount > 0) {
						outstr += "\nThe Attr of this Tag：";
						for (int i = 0; i < attrCount; i++) {
							outstr += parser.getAttributeName(i) + ":"
									+ parser.getAttributeValue(i);
						}
					}
					// 这里可以根据不同的 节点名称来作出不同的反应，比如text需要单独处理什么

				} else if (eventType == XmlPullParser.TEXT) {
					outstr += "\n[ A TEXT Tag `" + parser.getName() + "']";
					// 已经取不到值了
					outstr += parser.getText();
				} else if (eventType == XmlPullParser.END_TAG) {
					outstr += "\n[EXIT Tag `" + parser.getName() + "']";
                    //outstr += "\n" + parser.getText();
					// 可以在这这里把本tag的内容处理掉，比如类似将其放到某个容器中
				}

				eventType = parser.next();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println(outstr);
		return outstr;
	}

}
